package com.example.lin.http;

import com.alibaba.fastjson.JSONObject;
import com.example.lin.util.ExcelReadUtils;
import com.example.lin.util.MD5Utils;
import lombok.Data;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @className: EpassInfo
 * @description: epass 清洗小工具
 * @author: Lin.Gu
 * @date: 2025-10-31  13:57
 */
public class EpassInfo {

    // 请求模板
    RestTemplate restTemplate = RestTemplateProxy.getRestTemplate();
    // 正确获取线程池的方式
    ExecutorService executor = RestTemplateProxy.getCommonExecutor();

    @Test
    public void cleanEpassInfo() {
        //始发国家
        String country = "CN";
        String filePath = "C:\\Users\\181596\\Desktop\\UK 清洗数据信息108199.xlsx";
        //JP = 0 CN = 1,2,3,4,5
        int sheet = 0;
        List<LinkedHashMap<Integer, String>> dataList = ExcelReadUtils.readExcelToList(filePath, sheet);
        System.out.println("list size: " + dataList.size());
        AtomicInteger i = new AtomicInteger();

        //test
        String url = "http://10.238.237.101:9015/accept-client/v1/cleanEBayData";
        String apikey = "";
        String clientKey = "";
        String requestUrl = "";


//        //PROD
//        String url = "https://edcp-api-cn.orangeconnex.com/dcp/service/accept-client/v1/cleanEBayData";
//        String apikey = "b8cef4b1-657b-4fe3-a636-f65e833fad01";
//        String clientKey = "2ef7cc4d-5c7f-4729-aa71-3539b5ad7f18";
//        String requestUrl = url.split("com")[1];

        // 分批处理，每批3个元素
        int batchSize = 3;
        for (int start = 0; start < dataList.size(); start += batchSize) {
            int end = Math.min(start + batchSize, dataList.size());
            List<LinkedHashMap<Integer, String>> batch = dataList.subList(start, end);

            executor.submit(() -> {

                List<itemData> itemDataList = new ArrayList<>();
                batch.forEach(e -> {
                    String itemID = e.get(0);
                    String titleOriginal = e.get(1);
                    String link = e.get(2);
                    String imgLink = e.get(3);
                    String countryOfOrigin = e.get(4);
                    String variationSku = "";
                    String origin = country;
                    String dest = "GB";

                    itemData itemData = new itemData();
                    itemData.setBusinessId(itemID + System.currentTimeMillis());
                    itemData.setItemID(itemID);
                    itemData.setTitleOriginal(titleOriginal);
                    itemData.setLink(link);
                    itemData.setImgLink(imgLink);
                    itemData.setCountryOfOrigin(countryOfOrigin);
                    itemData.setVariationSku(variationSku);
                    itemData.setOrigin(origin);
                    itemData.setDest(dest);
                    itemDataList.add(itemData);
                });

                long timestamp = System.currentTimeMillis();
                JSONObject params = new JSONObject();
                params.put("messageId", timestamp + "" + getRandomNum());
                params.put("timestamp", timestamp);

                JSONObject itemJson = new JSONObject();
                itemJson.put("item", itemDataList);

                params.put("data", itemJson);

                //byte[] body = params.toJSONString().getBytes(StandardCharsets.UTF_8);
                //String paramString = new String(body, Charset.forName("UTF-8"));
                String paramString = params.toJSONString();

                System.out.println("请求报文：" + paramString);
                String signStr = requestUrl + "|" + paramString + "|" + apikey + "|" + clientKey;
                String serverSign = MD5Utils.sign(signStr, "UTF-8");
                //System.out.println("签名signString：" + signStr);
                //System.out.println("签名auth：" + serverSign);
                //增加请求头
                HttpHeaders headers = new HttpHeaders();
                headers.add(HttpHeaders.CONTENT_TYPE, "application/json");
                headers.add("ApiKey", apikey);
                headers.add("TimeStamp", String.valueOf(timestamp));
                headers.add("Authorization", serverSign);
                HttpEntity<String> entity = new HttpEntity(paramString, headers);

                //System.out.println("请求报文：" + params);
                String result = restTemplate.postForObject(url, entity, String.class);

                // 处理逻辑
                System.out.println("Processing: " + itemDataList.stream().map(itemData::getItemID).collect(Collectors.joining(","))
                        + ", Thread: " + Thread.currentThread().getName() + ", response: " + result);
            });
        }

        // 等待所有任务完成
        executor.shutdown();
        try {
            executor.awaitTermination(30, TimeUnit.MINUTES);
        } catch (Exception e) {
            Thread.currentThread().interrupt();
        }
    }


    @Data
    public static class itemData {
        private String businessId;
        private String project = "SPK";
        private Integer hscodeStandard = 10;
        private String platform = "eBay";
        private Integer needHscode = 1;
        private String orderOriginal = "SPK";
        private String code = "tri1,tri2";
        private String itemID;
        private String titleOriginal;
        private String link;
        private String imgLink;
        private String countryOfOrigin;
        private String variationSku;
        private String origin;
        private String dest;
        //code tri1,tri2
    }

    private Integer getRandomNum() {
        Random random = new Random();
        // 生成一个 1000 到 9999 之间的随机整数
        int randomNum = random.nextInt(9000) + 1000;
        return randomNum;
    }

}
